const express = require("express");
const path = require("path");
const fs = require("fs");
// 解析文件的中间件
const fileUpload = require("express-fileupload");
// 解析body的JSON格式内容
const bodyParser = require("body-parser");
const app = express();

app.get("/submit", (req, res) => {
  res.sendFile(path.resolve(__dirname, "submit.html"));
});
app.get("/submitb64", (req, res) => {
  res.sendFile(path.resolve(__dirname, "submitb64.html"));
});
app.get("/submitbinary", (req, res) => {
  res.sendFile(path.resolve(__dirname, "submitbinary.html"));
});

app.post("/submit", fileUpload(), (req, res) => {
  console.log(req.files); // 中间件fileUpload生成的
  // .file 是文件对象在表单上传的名称
  req.files.file.mv(path.resolve(__dirname, `upload/b.jpg`));
  res.status(201).send("OK");
});
app.post("/submitb64", bodyParser.json(), (req, res) => {
  const buffer = new Buffer(req.body.data, "base64");
  fs.writeFileSync(path.resolve(__dirname, "upload/x.jpg"), buffer);

  res.status(201).send("OK");
});
app.post("/submitbinary", fileUpload(), (req, res) => {
  console.log(req.files); // 中间件fileUpload生成的
  // .file 是文件对象在表单上传的名称
  req.files.file.mv(path.resolve(__dirname, `upload/c.jpg`));
  res.status(201).send("OK");
});

app.listen(3000, () => {
  console.log("3000 端口已启动");
});
